<?php


namespace App\Service\VendorClient\Shopsilkroad;


use Service\AppService\IdService;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;

class ShopsilkroadApiClient 
{
    private $account  = 'shopsilkroad';
    private $baseurl='https://billapi.eurcd.com/api/';
    private $routers  = [
        'createOrder'=>'open/send/data'
    ];
    protected $config;

    /**
     * 初始参数
     * @param array $apiBody
     */
    public function __construct( $apiBody = [] )
    {
        $this->config = $apiBody;
    }

    /**
     * 创建订单
     */
    public function createOrder( $param = [] )
    {
        $orderInfo  = $param['supplierOrder'];
        $goodsList  = $param['orderGoods'];
        $order      = $param['order'];
        $binfo      = $param['binfo'];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //实际下单金额 
        $real_total_money = $orderInfo['real_total_money'];

        //商品下单组
        $orderGoodsList = [];
        $productAmt     = $TaxAmt = 0 ;
        foreach ($goodsList as $key => $item )
        {
            //卖价
            $price          = $item['price'];
            //商品购买规格数量
            $spec_num       = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity       = $item['quantity'];
            //实际购买数量
            $buyAcount      = $spec_num * $quantity ;
            //商品单价包含税金
            if( $key == 0 ) {
                $dev_money   = bcdiv((string)$deliver_money, (string)$quantity,3);
                $dev_money   = bcmul((string)$dev_money,'100',1);
                $dev_money   = bcdiv((string)ceil($dev_money),'100',2);
                $price       = bcadd((string)$price, (string)$dev_money,2);
            }

            //商品税率
            $tax                = $item['tax_rate'];
            $tax_rate           = bcadd((string)$tax,'1.0000',4);

            //单价含税单价需要把第三位往上收取，不能单独不含税价和税金分开计算，需要做减法
            $singlePrice        = bcdiv((string)$price, (string)$spec_num,3);
            $singlePrice        = bcmul((string)$singlePrice,'100',1);
            $singlePrice        = bcdiv((string)ceil($singlePrice),'100',2);

            //不含税价格
            $notTaxGoodsSinglePrice = bcdiv((string)$singlePrice, $tax_rate,3);
            $notTaxGoodsSinglePrice = bcmul((string)$notTaxGoodsSinglePrice,(string)'100',1);
            $notTaxGoodsSinglePrice = bcdiv((string)ceil($notTaxGoodsSinglePrice),'100',2);

            $buyNum             = $spec_num * $quantity;
            $goodsTotalPrice    = bcmul((string)$notTaxGoodsSinglePrice,(string)$buyNum,2);

            //商品关税当前币种最小单位（分）
            $goodsCustomsTax    = bcsub((string)$singlePrice,(string)$notTaxGoodsSinglePrice,2);
            $taxAll             = bcmul($goodsCustomsTax,(string)$buyNum,2);

            //商品组
            $orderGoodsList[] = [
                'itemNo'                => $item['supplier_skucode'],
                'count'                 => $buyAcount,
                'price'                 => $notTaxGoodsSinglePrice,
                'totalPrice'            => $goodsTotalPrice,
            ];

            $productAmt = bcadd((string)$productAmt,(string)$goodsTotalPrice,2);
            $TaxAmt = bcadd((string)$TaxAmt,(string)$taxAll ,2);
        }
        $ActualPaidAmt  = bcadd((string)$TaxAmt,(string)$productAmt,2);
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        $payTime        = empty($order['payTime']) ? $orderInfo['pay_time'] :$order['payTime'];
        //支付时间
        $pay_time       = $payTime ? $payTime : time();

        //支付流水号
        $pay_sn         = $order['paySerial']??$orderInfo['pay_sn'];
        
        //优惠金额
        $discount_money = bcsub((string)$ActualPaidAmt,(string)$orderInfo['real_total_money'],2);

        $address = $orderInfo['province'].$orderInfo['city'].$orderInfo['district'].$orderInfo['receive_address'];
        //创建订单数据
        $data = [
            //下单基础信息
            'customs'                 => $this->config['customs'],
            'shopId'                  => $this->config['shopId'],
            'orderNo'                 => $orderInfo['supplier_dsn'],
            'is_push_order'           => 1,
            'is_push_payment'         => 0,
            'is_push_logistics'       => 1,
            'is_push_inventory'       => 1,
            'ebpCode'                 => $order['enterpriseNum'] ?? $apply_extends['enterpriseNum'],
            'ebpName'                 => $order['enterpriseName'] ?? $apply_extends['enterpriseName'],
            'payCode'                 => $order['payCommanyCode'] ?? $apply_extends['payCommanyCode'],
            'payName'                 => $order['payCommanyName'] ?? $apply_extends['payCommanyName'],
            'consignee'               => $orderInfo['receive_name'],
            'consigneeAddress'        => $address,
            'consigneeTelephone'      => $orderInfo['recveive_phone'],
            'copNo'                   => $orderInfo['supplier_dsn'],
            'buyerIdNumber'           => $orderInfo['buyer_idcard'],
            'buyerName'               => $orderInfo['buyer_realname'],
            'buyerTelephone'          => $orderInfo['buyer_phone'],
            'transactionId'           => $pay_sn,
            'goodsValue'              => $productAmt,
            'freight'                 => "0.00",//分摊了运费,就不需要传运费了
            'discount'                => $discount_money,
            'taxTotal'                => $TaxAmt,
            'acturalPaid'             => $real_total_money,
            'goods'                   => json_encode($orderGoodsList,JSON_UNESCAPED_UNICODE)
        ];
        //开始请求
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => $data
        ];
        return $this->execute($requestParam);
        
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }

        $method = $param['method'];
        $route = $this->routers[$method];
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $this->baseurl.$route,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'json',
                'header'    => ["Content-Type: application/json"],
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res,true);
        if( isset($resHttp['code']) && $resHttp['code'] ==0 ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        $message = isset($resHttp['msg']) ? $resHttp['msg'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }

}